<template>
    <div>
        <basic-layout title="我的邀请" :showAddBtn="false">
            <div class="columnBg">
                <van-form ref="form">
                    <van-field clickable name="来访人名称" label="来访人名称" required maxlength="128" v-model="formData.visitor" placeholder="请输入来访人名称" :rules=rules.visitor />
                    <div class="photoRow">
                        <div>
                            <div class="left">
                                <p>照片</p>
                                <p>上传高清正面图，用于人脸识别</p>
                            </div>
                            <div class="right">
                                <uploadCom ref="uploadRef" :maxNumber="1" @uploadFileIds="uploadFileIds" accept=".jpg,.jpeg,.png"></uploadCom>
                            </div>
                        </div>
                    </div>
                    <van-field name="来访人性别" label="来访人性别">
                        <template #input>
                            <van-radio-group v-model="formData.visitorSex" direction="horizontal">
                                <van-radio :name="item.value" v-for="item in sexList" :key="item.value">{{item.name}}</van-radio>
                            </van-radio-group>
                        </template>
                    </van-field>
                    <van-field v-model="formData.visitorCertNo" required name="证件号码" label="证件号码" maxlength="18" type="text" placeholder="请输入证件号码" :rules=rules.visitorCertNo>
                        <template #label>
                            <van-dropdown-menu class="typeMenu">
                                <van-dropdown-item v-model="formData.visitorCertType" :options="certTypeList" />
                            </van-dropdown-menu>
                        </template>
                    </van-field>
                    <van-field v-model="formData.visitorCorpName" name="邀请单位" label="邀请单位" maxlength="256" type="text" placeholder="请输入邀请单位" :rules=rules.visitorCorpName />
                    <van-field v-model="formData.visitorPhone" required name="联系电话" label="联系电话" maxlength="11" type="text" placeholder="请输入联系电话" :rules="formData.visitorPhone ? rules.visitorPhone : null" />
                    <van-field readonly clickable name="来访时间" is-link label="来访时间" required :value="formData.visitTime" placeholder="请选择来访时间" @click="showChooseTimeComp" :rules=rules.visitTime />
                    <van-field readonly clickable name="离开时间" is-link label="离开时间" required :value="formData.departureTime" placeholder="请选择离开时间" @click="showChooseTimeComp" :rules=rules.departureTime />
                    <van-field readonly name="邀请事由" label="邀请事由" required :value="formData.visitReason" placeholder="请选择邀请事由" :rules=rules.visitReason>
                        <template #input>
                            <van-tag v-for="(item, ind) in visitReasonList" :color="tagColor[ind] || '#4eb3e9'" :plain="item.value !== formData.visitReason" @click="onReasonConfirm(item)">{{item.name}}</van-tag>
                        </template>
                    </van-field>
                    <van-field readonly clickable :value="formData.plateNumber" name="车牌号" label="车牌号" maxlength="16" type="text" placeholder="请输入车牌号" @click="showChoosePlate = true" :rules="formData.plateNumber ? rules.plateNumber : null" />
                </van-form>
                <div class="followerBox">
                    <h5 @click="isFold = !isFold;">
                        随行人员信息（{{followerList.length}}人）
                        <p v-if="isFold">展开 <van-icon name="arrow-down" /></p>
                        <p v-else>折叠 <van-icon name="arrow-up" /></p>
                        <van-button size="mini" round type="info" icon="plus" :disabled="followerList.length >= 5" @click="handleAdd"></van-button>
                    </h5>
                    <div v-show="!isFold" class="list">
                        <div v-for="(val, ind) in followerList" :key=ind class="list-item">
                            <img :src="val.url || 'images/convaccess/people.svg'">
                            <div class="right">
                                <div>
                                    <label>姓名：</label>
                                    <p>{{val.follower || "-"}}{{val.followerSexName ? ('（' + val.followerSexName + '）') : ''}}</p>
                                </div>
                                <div>
                                    <label>手机号：</label>
                                    <p>{{val.followerPhone || "-"}}</p>
                                </div>
                                <div>
                                    <label>{{val.visitorCertTypeName}}：</label>
                                    <p>{{(val.visitorCertType === '1' ? $infoHiding.handleIdCard(val.visitorCertNo) : val.visitorCertNo) || "-"}}</p>
                                </div>
                                <div>
                                    <label>来访单位：</label>
                                    <p>{{val.visitorCorpName || "-"}}</p>
                                </div>
                            </div>
                            <van-button plain color="#ee0a24" @click="handleDelete(ind)">删除</van-button>
                        </div>
                        <van-empty v-if="!followerList.length" class="custom-image" :image="require('../../../../assets/images/empty.png')" description="暂无随行人员" />
                    </div>
                </div>
                <van-button class="defaultBtn" @click="handleSave">保存并生成邀请码</van-button>
            </div>
        </basic-layout>
        <!-- 选择来访时间 -->
        <van-popup v-model="showChooseTime" position="bottom" :style="{'height': '75%'}">
            <chooseDateTime title="来访" ref="chooseDateTimeRef" @close="showChooseTime = false" @sendTime="getVisitTime" />
        </van-popup>
        <!-- 选择访客中心 -->
        <van-dialog v-model="showDialog" title="访客中心选择" :showConfirmButton="false">
            <ul class="centerListBox">
                <li v-for="item in centerList" :key="item.centerId" @click="changeCenter(item)">
                    {{item.centerName}}
                    <van-icon name="success" v-if="item.centerId === formData.centerId" />
                </li>
            </ul>
        </van-dialog>
        <!-- 随行人员信息 -->
        <van-popup v-model="showVanPopup" position="bottom" :close-on-click-overlay="false" :style="{'height': '66%'}">
            <div class="addFormBox">
                <p>随行人员信息<van-icon size="20" name="cross" @click="showVanPopup = false" /></p>
                <div>
                    <addForm ref="addFormRef" @sendForm="getAddFollower" @close="showVanPopup = false;"></addForm>
                </div>
            </div>
        </van-popup>
        <!-- 车牌号 -->
        <vnp-keyboard v-model="formData.plateNumber" :show.sync="showChoosePlate"></vnp-keyboard>
        <fullLoading v-if="loading"></fullLoading>
    </div>
</template>

<script>
    import { queryDic } from '@api/common';
    import { addVisitors } from '@/api/srvAssurance/convaccess/myInvitation';
    import { queryInterviewerByCorpIdList, getByCenterId, getBlackListByCertNo } from '@/api/srvAssurance/convaccess/appointmentVisit';
    import addForm from '../appointmentVisit/addForm.vue';
    import chooseDateTime from '../appointmentVisit/chooseDateTime.vue';
    import vnpKeyboard from '@/components/vant-number-plate/vnp-keyboard';

    export default {
        components: { addForm, chooseDateTime, vnpKeyboard },
        data () {
            return {
                loading: false,
                showChooseTime: false,
                showDialog: false,
                showVanPopup: false,
                isFold: true,
                showChoosePlate: false,
                formData: {
                    centerId: '',
                    visitor: '', // 来访人名称
                    visitorPhoto: '', // 照片
                    visitorSex: '', // 来访人性别
                    visitorCertType: '', // 证件类型
                    visitorCertNo: '', // 证件号码
                    visitorCorpName: '', // 邀请单位
                    visitorPhone: '', // 联系电话
                    visitTime: '', // 来访时间
                    departureTime: '', // 离开时间
                    visitTimeDateStr: '',
                    visitReason: '', // 邀请事由
                    plateNumber: '', // 车牌号
                },
                rules: {
                    visitor: [
                        { required: true, message: '请输入来访人名称', trigger: 'onBlur' },
                        { pattern: this.$commonReg.textReg, message: this.$commonReg.textMsg, trigger: 'onBlur' }
                    ],
                    visitTime: [
                        { required: true, message: '请选择来访时间', trigger: 'onChange' }
                    ],
                    departureTime: [
                        { required: true, message: '请选择离开时间', trigger: 'onChange' }
                    ],
                    visitReason: [
                        { required: true, message: '请选择邀请事由', trigger: 'onChange' }
                    ],
                    visitorCorpName: [
                        { pattern: this.$commonReg.textReg, message: this.$commonReg.textMsg, trigger: 'onBlur' }
                    ],
                    visitorPhone: [
                        { pattern: this.$commonReg.phoneReg, message: this.$commonReg.phoneMsg, trigger: 'onBlur' }
                    ],
                    visitorCertNo: [
                        { required: true, message: '请输入证件号码', trigger: 'onBlur' },
                        { pattern: this.$commonReg.textReg, message: this.$commonReg.textMsg, trigger: 'onBlur' }
                    ],
                    plateNumber: [
                        { required: true, message: '请输入车牌号', trigger: 'onChange' },
                        { pattern: /^[\u4e00-\u9fa5]{1}[A-Z]{1}[A-Z_0-9]{5,6}$/, message: '请输入正确的车牌号', trigger: 'onChange' }
                    ]
                },
                certTypeList: [], // 证件类型
                sexList: [], // 性别
                visitReasonList: [], // 邀请事由
                pickerStartTime: new Date(),
                pickerEndTime: new Date(),
                tagColor: ['#4eb3e9', '#07c160', '#ff976a', '#7232dd'],
                followerList: [], // 随行人员列表
                centerList: [],
                centerConfig: {
                    entourageNum: '', // 随行人员数量
                    advanceReservationDay: '', // 可提前预约天数
                    continuousReservationMaxday: '', // 连续预约最大天数
                    beginTime: '', // 起始时间
                    endTime: '', // 截止时间
                    week: ''
                },
                isBlackList: false
            };
        },
        created () {
            this.getDicData();
        },
        methods: {
            // 提交
            handleSave () {
                this.$refs.form.validate().then(async () => {
                    await this.getBlackListByCertNoData();
                    if (this.isBlackList) {
                        return
                    }
                    let start = new Date(this.formData.visitTime);
                    let end = new Date(this.formData.departureTime);
                    if (start > end) {
                        this.$Notify({ type: 'warning', message: '来访时间不能大于离开时间！' });
                        return
                    }
                    let formData = {
                        ...this.formData,
                        visitMethod: '02',
                        visitType: '',
                        visitorsEntourageSaveList: this.followerList
                    }
                    formData.visitTime = new Date(this.formData.visitTime).getTime(); // 来访时间
                    formData.departureTime = new Date(this.formData.departureTime).getTime(); // 离开时间
                    this.loading = true;
                    addVisitors(formData).then(res => {
                        this.loading = false;
                        if (res.code === 1000) {
                            this.$Dialog.confirm({
                                title: '保存成功！',
                                cancelButtonText: '新建预约拜访',
                                confirmButtonText: '查看邀请记录'
                            }).then(() => {
                                this.$router.push({ name: 'convaccess-accessRecord', params: { activeName: 'myInvite' } })
                            }).catch(() => {
                                this.handleReset();
                            });
                        }
                    }).catch(() => {
                        this.loading = false;
                    })
                })
            },
            // 附件上传
            uploadFileIds (arr) {
                this.formData.visitorPhoto = arr[0];
            },
            // 选择邀请事由
            onReasonConfirm (item) {
                this.formData.visitReason = item.value;
            },
            // 选择拜访时间
            showChooseTimeComp () {
                this.showChooseTime = true;
                this.$nextTick(() => {
                    this.$refs.chooseDateTimeRef.getCenterConfig(this.centerConfig);
                })
            },
            getVisitTime (params) {
                this.formData.visitTime = params.visitTime;
                this.formData.departureTime = params.departureTime;
                this.formData.visitTimeDateStr = params.visitTimeDateStr;
            },
            // 添加随行人员
            handleAdd (e) {
                e.stopPropagation();
                if (this.centerConfig.entourageNum && this.followerList.length >= this.centerConfig.entourageNum) {
                    this.$Notify({ type: "warning", message: `最多可添加${this.centerConfig.entourageNum}位随行人员！` });
                    return;
                }
                this.showVanPopup = true;
                this.$nextTick(() => {
                    this.$refs.addFormRef.resetForm();
                })
            },
            // 获取添加的人员信息
            getAddFollower (item) {
                this.followerList.push(item);
                if (this.isFold) this.isFold = false;
            },
            // 删除
            handleDelete (index) {
                this.followerList.splice(index, 1);
            },
            // 重置
            handleReset () {
                this.isFold = true;
                this.isBlackList = false;
                this.formData = {
                    centerId: '',
                    visitor: '', // 来访人名称
                    visitorPhoto: '', // 照片
                    visitorSex: '', // 来访人性别
                    visitorCertType: '', // 证件类型
                    visitorCertNo: '', // 证件号码
                    visitorCorpName: '', // 邀请单位
                    visitorPhone: '', // 联系电话
                    visitTime: '', // 来访时间
                    departureTime: '', // 离开时间
                    visitTimeDateStr: '',
                    visitReason: '', // 邀请事由
                    plateNumber: '', // 车牌号
                };
                for (var key in this.centerConfig) {
                    this.centerConfig[key] = res.data[key] || '';
                }
                this.pickerStartTime = new Date();
                this.pickerEndTime = new Date();
                this.followerList = []; // 随行人员列表
                this.$refs.uploadRef.reset();
                setTimeout(() => {
                    this.$refs.form.resetValidation();
                    if (this.certTypeList.length) {
                        this.formData.visitorCertType = this.certTypeList[0].value;
                    }
                    if (this.sexList.length) {
                        this.formData.visitorSex = this.sexList[0].value;
                    }
                })
            },
            // 切换访客中心
            changeCenter (item) {
                this.formData.centerId = item.centerId;
                setTimeout(() => {
                    this.showDialog = false;
                    this.changeCenterResetData();
                    this.getByCenterIdData(item.centerId);
                    this.getBlackListByCertNoData();
                }, 300)
            },
            // 判断是否在黑名单获取黑名单
            async getBlackListByCertNoData () {
                this.isBlackList = false;
                if (!this.formData.visitorCertNo || !this.formData.centerId) return;
                await getBlackListByCertNo(this.formData.centerId, this.formData.visitorCertNo).then(res => {
                    if (res.code === 1000 && res.data) {
                        this.isBlackList = true;
                        if (this.centerList.length > 1) {
                            this.$Dialog.confirm({
                                message: '该来访人已被该访客中心拉入黑名单！',
                                confirmButtonText: '切换访客中心',
                                cancelButtonText: '取消'
                            }).then(() => {
                                this.showDialog = true;
                            }).catch(() => { })
                        } else {
                            this.$Dialog.alert({
                                message: '该来访人已被访客中心拉入黑名单！',
                            }).then(() => { })
                        }
                    }
                })
            },
            // 切换访客中心部分信息重置
            changeCenterResetData () {
                this.formData.visitTime = '';
                this.formData.departureTime = '';
                this.formData.visitTimeDateStr = '';
                this.centerConfig = {
                    entourageNum: '', // 随行人员数量
                    advanceReservationDay: '', // 可提前预约天数
                    continuousReservationMaxday: '', // 连续预约最大天数
                    beginTime: '', // 起始时间
                    endTime: '', // 截止时间
                    week: ''
                }
                if (this.$refs.chooseDateTimeRef) {
                    this.$refs.chooseDateTimeRef.getCenterConfig(this.centerConfig, this.formData.visitTime && this.formData.departureTime);
                }
            },
            // 获取访客中心配置信息
            getByCenterIdData (centerId) {
                getByCenterId(centerId).then(res => {
                    if (res.code === 1000 && res.data) {
                        for (var key in this.centerConfig) {
                            this.centerConfig[key] = res.data[key] || '';
                        }
                        this.getLimitByCertNoData(centerId);
                        this.getPhotoByCertNoData(centerId);
                    }
                })
            },
            // 标准代码
            getDicData () {
                // 访客中心
                queryInterviewerByCorpIdList().then(res => {
                    if (res.code === 1000 && res.data) {
                        this.centerList = res.data;
                        if (this.centerList.length === 1) {
                            this.changeCenter(this.centerList[0]);
                        } else if (this.centerList.length > 1) {
                            this.showDialog = true;
                        } else {
                            this.$Dialog.alert({
                                message: '请先配置访客中心',
                            }).then(() => { });
                        }
                    }
                })
                // 证件类型
                queryDic('CERT_TYPE_CODE').then(res => {
                    if (res.code === 1000 && res.data) {
                        this.certTypeList = res.data;
                        if (this.certTypeList.length) {
                            this.formData.visitorCertType = this.certTypeList[0].value;
                        }
                    }
                })
                // 性别
                queryDic('SEX_FLAG_CODE').then(res => {
                    if (res.code === 1000 && res.data) {
                        this.sexList = res.data.filter(item => item.value !== '3');
                        if (this.sexList.length) {
                            this.formData.visitorSex = this.sexList[0].value;
                        }
                    }
                })
                // 邀请事由
                queryDic('SA_VISITORS_REASON').then(res => {
                    if (res.code === 1000 && res.data) {
                        this.visitReasonList = res.data;
                    }
                })
            }
        },
    };
</script>

<style scoped lang="less">
    .columnBg {
        overflow: auto;
        background: #eee;
        .photoRow {
            background: #fff;
            padding: 8px 15px;
            box-sizing: border-box;
            & > div {
                width: 100%;
                display: flex;
                align-items: center;
                justify-content: space-between;
                position: relative;
                .left {
                    line-height: 25px;
                    p:nth-of-type(2) {
                        color: #999;
                        font-size: 12px;
                    }
                }
            }
            & > div::after {
                position: absolute;
                box-sizing: border-box;
                content: " ";
                pointer-events: none;
                right: 0.42667rem;
                bottom: -8px;
                left: 0.42667rem;
                border-bottom: 0.02667rem solid #ebedf0;
                -webkit-transform: scaleY(0.5);
                transform: scaleY(0.5);
            }
        }
        .checkBox {
            position: relative;
            /deep/.van-checkbox__icon {
                font-size: 17px;
                position: absolute;
                right: 0;
            }
        }
    }
    .van-form {
        border-bottom: 1px solid #f1f1f2;
        .typeMenu {
            /deep/.van-dropdown-menu__bar {
                height: 20px;
                line-height: 20px;
                box-shadow: none;
                font-size: 13px;
                .van-dropdown-menu__title::after {
                    border-color: transparent transparent #272c30 #272c30;
                }
                .van-dropdown-menu__title {
                    padding-left: 0;
                    font-size: 14px;
                    color: #646566;
                }
                .van-dropdown-menu__item {
                    justify-content: flex-start;
                }
            }
        }
        /deep/.van-radio__icon {
            font-size: 16px;
        }
        .van-tag {
            margin-right: 10px;
            line-height: 22px;
            padding: 0 8px;
        }
    }
    h5 {
        border-bottom: 1px solid #f1f1f2;
        line-height: 40px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 15px;
        font-weight: normal;
        color: #888;
        position: relative;
        /deep/.van-button--mini {
            padding: 0;
            width: 18px;
            height: 18px;
        }
        p {
            position: absolute;
            right: 45px;
        }
    }
    .followerBox {
        background: #fff;
        margin-top: 5px;
        h5 {
            background: #fff;
        }
        /deep/.van-empty {
            padding: 20px 0;
            .van-empty__image {
                width: 50px;
                height: 50px;
            }
        }
        .list-item {
            display: flex;
            padding: 10px;
            box-sizing: border-box;
            align-items: center;
            img {
                width: 60px;
                height: 60px;
                margin-right: 10px;
            }
            .right {
                flex: 1;
                overflow: hidden;
                div {
                    display: flex;
                    line-height: 22px;
                    align-items: center;
                    font-size: 12px;
                    label {
                        color: #999;
                    }
                    p {
                        flex: 1;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                    }
                }
            }
            .van-button {
                height: 25px;
                padding: 0 10px;
                font-size: 12px;
            }
        }
    }
    .addFormBox {
        position: relative;
        p {
            text-align: center;
            line-height: 45px;
            font-size: 14px;
            margin-bottom: 5px;
            border-bottom: 1px solid #eee;
            color: #666;
        }
        & > div {
            padding: 0 10px;
            box-sizing: border-box;
        }
        .van-icon {
            position: absolute;
            right: 10px;
            top: 10px;
        }
    }
    .van-dialog {
        /deep/.van-dialog__header {
            padding: 10px 0;
        }
        .centerListBox {
            height: 180px;
            padding: 0 15px;
            line-height: 32px;
            font-size: 14px;
            overflow: auto;
            box-sizing: border-box;
            margin-bottom: 10px;
            li {
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                position: relative;
                padding-right: 30px;
                box-sizing: border-box;
                .van-icon {
                    position: absolute;
                    font-size: 18px;
                    top: 5px;
                    right: 0;
                    color: #4eb3e9;
                }
            }
        }
    }
    .defaultBtn {
        margin-top: 15px;
    }
</style>